<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/17
 * Time: 12:46
 */

namespace App\gen;


class CurdGenerator
{
    use DbGenerator;
    /**
     * @var \App\Console\Commands\GenCurd
     */
    static $console = null ;
    static $colmns = [] ;
    public static function build($console,$colmns){

        self::$console = $console ;
        self::$colmns = self::formatColmns($colmns) ;
        self::buildCreate();
        self::buildController();
        self::buildIndex();
    }


    public static function buildIndex(){
        $colmns = self::$colmns ;
        $className = self::$console->argument('className');
        $dir = snake_case($className) ;

        $view = self::$console->option('view');

        ob_start();
        include __DIR__ . '/stub/index.stub.php';
        $content = ob_get_contents();
        ob_end_clean();
        $filename = base_path('resources/views/backend/'.$view.'/index.blade.php') ;
        self::checkPath($filename);
        file_put_contents($filename,$content) ;
    }

    public static function buildController(){

        $className = self::$console->argument('className');
        $classNameArr = explode('/',$className) ;
        $trueClassName = array_pop($classNameArr) ;
        $subControllerNameSpace = implode('\\',$classNameArr);
        if($subControllerNameSpace){
            $subControllerNameSpace = '\\'.$subControllerNameSpace ;
        }

        $model = self::$console->option('model');
        $modelArr = explode('/',$model) ;
        $trueModelName = array_pop($modelArr) ;
        $subNameSpace = str_replace('/','\\',$model);

        $view = self::$console->option('view');
        $viewSpace = str_replace('/','.',$view) ;

        ob_start();
        include __DIR__ . '/stub/contrller.stub.php';
        $content = ob_get_contents();
        ob_end_clean();

        $filename = base_path("app/Http/Controllers/backend/{$className}Controller.php") ;
        self::checkPath($filename);
        file_put_contents($filename,$content) ;
    }

    public static function buildCreate(){

        $dir = snake_case(self::$console->argument('className')) ;
        $colmns = self::$colmns ;


        $view = self::$console->option('view');
        $viewSpace = str_replace('/','.',$view) ;

        ob_start();
        include __DIR__ . '/stub/create.stub.php';
        $content = ob_get_contents();
        ob_end_clean();
        $filename = base_path('resources/views/backend/'.$view.'/save.blade.php') ;
        self::checkPath($filename);
        file_put_contents($filename,$content) ;
    }

    public static function checkPath($path){
        $dirName = dirname($path) ;
        if(!file_exists($dirName)){
            mkdir($dirName,0777,true);
        }
    }




}